<template>
  <div>
            <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-button type="primary" @click="addRoles">添加角色</el-button>
                <!-- 列表区域 -->
      <el-table
        :data="rolesList" border  style="width: 100%">
         <el-table-column type="expand">
            <template slot-scope="scope">
              <el-row :class="['borderBottom','vcenter',id1==0?'borderTop':'']" v-for="(item1,id1) in scope.row.children" :key="id1">
                <!-- 渲染一级权限 -->
                <el-col :span="5">
                  <el-tag closable @close="deleteRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                                    <!-- 加上图标 -->
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 渲染二级和三级权限 -->
                <el-col :span="19">
                  <el-row :class="['borderBottom','vcenter',id2==0?'':'borderTop']" v-for="(item2,id2) in item1.children" :key="id2">
                    <!-- 渲染二级权限 -->
                    <el-col :span="6">
                      <el-tag closable @close="deleteRightById(scope.row,item2.id)" type="success" >{{item2.authName}}</el-tag>
                                        <!-- 加上图标 -->
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <!-- 渲染 三级权限 -->
                    <el-col :span="18">
                      <!-- 删除函数，第一个参数传递的是role相关信息，第二个参数传递的是权限id -->
                      <el-tag closable @close="deleteRightById(scope.row,item3.id)" type="warning" v-for="(item3,id3) in item2.children" :key="id3">{{item3.authName}}</el-tag>
                                        <!-- 加上图标 -->
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
        </el-table-column>
        <el-table-column  label="#" width="180" type="index"> </el-table-column>
        <el-table-column  prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column  prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary"  icon="el-icon-edit" @click="editRoleInfo(scope.row.id)" ></el-button>
            <el-button  size="mini"  type="danger"  icon="el-icon-delete" @click="deleteRoleInfo(scope.row.id)" ></el-button>
            <el-tooltip class="item" effect="dark" content="分配权限" placement="top-start">
              <el-button  size="mini"  type="warning"  icon="el-icon-setting" @click="allotRights(scope.row)" ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
            <!-- 分配权限对话框 -->
      <el-dialog
          title="分配权限"
          :visible.sync="allotRightsDialogVisible"
          width="50%" @close="setRightDialogClosed">
          <el-tree
            :data="rightsList" show-checkbox default-expand-all node-key="id" ref="treeRef"  highlight-current
            :props="defaultProps" :default-checked-keys="defKeys">
          </el-tree>
          <span slot="footer" class="dialog-footer">
            <el-button @click="allotRightsDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitallotRights">确 定</el-button>
          </span>
      </el-dialog>
            <!-- 修改角色对话框 -->
      <el-dialog
          title="修改角色"
          :visible.sync="editRoleDialogVisible"
          width="50%">
          <el-form ref="editRolesFormRef" :model="eidtRolesForm" label-width="80px" :rules="editRolesFormRules">
            <el-form-item label="角色名称"  prop="roleName">
              <el-input v-model="eidtRolesForm.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述"  prop="roleDesc">
              <el-input v-model="eidtRolesForm.roleDesc"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="editRoleDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitEditRole">确 定</el-button>
          </span>
      </el-dialog>
              <!-- 添加角色的对话框 -->
    <el-dialog title="添加角色" :visible.sync="addRolesDialogVisible"
      width="50%" @close="closeAddRolesForm">
      <el-form :model="addRolesForm" :rules="addRolesFormRules" ref="addRolesFormRef" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesForm.roleName"></el-input>
        </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddRolesForm">确 定</el-button>
      </span>
    </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 角色列表
      rolesList: [],
      // 编辑角色对话框
      editRoleDialogVisible: false,
      eidtRolesForm: {
      },
      // 修改用户表单的验证规则
      editRolesFormRules: {
        roleName: [
          { required: true, message: '请选择角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      // 添加角色对话框
      addRolesDialogVisible: false,
      addRolesForm: {},
      // 添加角色表单的验证规则
      addRolesFormRules: {
        roleName: [
          { required: true, message: '请选择角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      // 所有的权限
      rightsList: [],
      // 分配权限对话框
      allotRightsDialogVisible: false,
      // 树形控件绑定的对象
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      // 该角色已经默认选中的节点id
      defKeys: [],
      // 分配权限的id
      roleId: ''
    }
  },
  methods: {
    // 获取角色列表
    async getRolessList () {
      const { data: res } = await this.$http.get('roles')
      console.log(res)
      this.rolesList = res.data
    },
    // 添加角色
    addRoles () {
      this.addRolesDialogVisible = true
    },
    // 编辑角色列表
    async editRoleInfo (id) {
      const { data: res } = await this.$http.get(`roles/${id}`)
      console.log(res)
      this.eidtRolesForm = res.data
      this.editRoleDialogVisible = true
    },
    // 删除角色列表
    deleteRoleInfo (id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`roles/${id}`)
        // console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('删除角色失败')
        } else {
          this.$message.success(res.meta.msg)
          this.getRolessList()
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    // 删除角色下的相应权限
    deleteRightById (row, rightId) {
      // console.log(row)
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`roles/${row.id}/rights/${rightId}`)
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('删除权限失败')
        } else {
          this.$message.success(res.meta.msg)
          // 删除权限成功，为了避免重刷整个页面，只需要改变children的数据
          // this.getRolessList()
          // 此时返回的res.data就是删除之后剩下的权限
          row.children = res.data
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    // 提交修改角色对话框
    submitEditRole () {
      this.$refs.editRolesFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.put(`roles/${this.eidtRolesForm.roleId}`,
            {
              roleName: this.eidtRolesForm.roleName,
              roleDesc: this.eidtRolesForm.roleDesc
            })
          if (res.meta.status !== 200) {
            this.$message.error('修改失败')
          } else {
            this.$message.success('修改成功')
            this.editRoleDialogVisible = false
            this.getRolessList()
          }
        } else {
          return false
        }
      })
    },
    // 添加角色对话框关闭的时候，需要清空
    closeAddRolesForm () {
      this.$refs.addRolesFormRef.resetFields()
    },
    // 提交添加用户对话框
    submitAddRolesForm () {
      this.$refs.addRolesFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.post('roles',
            {
              roleName: this.addRolesForm.roleName,
              roleDesc: this.addRolesForm.roleDesc
            })
          if (res.meta.status !== 201) {
            this.$message.error('添加失败')
          } else {
            this.$message.success('添加成功')
            this.addRolesDialogVisible = false
            this.getRolessList()
          }
        } else {
          return false
        }
      })
    },
    // 点击分配权限，弹出对话框
    async allotRights (row) {
      console.log(row)
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        this.$message.error('获取权限失败')
      } else {
        this.rightsList = res.data
        // console.log(this.rightsList)
        // 获取三级权限的id
        this.getLeafKeys(row, this.defKeys)
        // console.log(this.defKeys)
        this.allotRightsDialogVisible = true
        // 存储当前角色的 id
        this.roleId = row.id
      }
    },
    // 监听分配权限的对话框的关闭（防止三级权限defKeys越来越多）
    setRightDialogClosed () {
      this.defKeys = []
    },
    // 获取该角色下所有已存在的三级权限的id
    getLeafKeys (node, arr) {
      if (node.children == null) {
        return arr.push(node.id)
      } else {
        node.children.forEach(item => {
          this.getLeafKeys(item, arr)
        })
      }
    },
    // 分配权限对话框的提交
    async submitallotRights () {
      const keysId = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // 需要将数组转换成字符串
      const keysIdStr = keysId.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, {
        rids: keysIdStr
      })
      if (res.meta.status === 200) {
        this.$message.success(res.meta.msg)
        this.allotRightsDialogVisible = false
        this.getRolessList()
      } else {
        this.$message.error('授权失败')
      }
    }
  },
  created () {
    this.getRolessList()
  }
}
</script>

<style scoped>
.el-table{
  margin-top: 15px
}
.borderTop{
  border-top: 1px solid #eeeeee
}
.borderBottom{
  border-bottom: 1px solid #eeeeee
}
/* 竖直方向上垂直居中 */
.vcenter{
  display: flex;
  align-items: center;
}
.el-tag{
  margin: 7px;
}
</style>
